package collect

import (
	"fmt"
	"path/filepath"
	"strings"

	"gitee.com/xuesongtao/collect/library"
	"gitee.com/xuesongtao/gotool/xfile"
	pslog "gitee.com/xuesongtao/ps-log"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/glog"
)

// GetCollectProjects 获取待处理的项目
func GetCollectProjects() ([]*CollectProject, error) {
	if collectProjects != nil {
		return collectProjects, nil
	}

	datas := make([]*CollectProject, 0, 10)
	collectConfigs := filepath.Join(library.GetCurProjectDir(), "config", "collect_config")
	fileObj := xfile.NewParseFile()
	fileObj.ParseHasSuffixFiles(collectConfigs, collectConfigFilenameSuffix)
	for _, fl := range fileObj.GetProFiles() {
		var data CollectProject
		err := library.UnmarshalFormFile(fl.AbsolutePath, &data)
		if err != nil {
			glog.Error("file.UnmarshalFormFile is failed, err:", err)
			continue
		}
		data.CfgFilename = fl.AbsolutePath
		if data.Ignore {
			glog.Warningf("%q set ignore, it will skip collect", data.CfgFilename)
			continue
		}
		datas = append(datas, &data)
	}
	collectProjects = datas
	return collectProjects, nil
}

func genPsLogExt(projectName string, appName string) string {
	if appName == "" {
		return ""
	}
	return projectName + "#" + appName
}

func parsePsLogExt(in string) (projectName string, appName string) {
	tmpIn := strings.Split(in, "#")
	if len(tmpIn) != 2 {
		return
	}
	projectName = tmpIn[0]
	appName = tmpIn[1]
	return
}

// getPushLogTitle 获取推送的日志的标题
func getPushLogTitle(projectName, appName string) (title string) {
	envName := "prd"
	if g.Cfg().GetBool("business.isTest") {
		envName = "dev"
	}
	return fmt.Sprintf(ErrLogTitle, envName, projectName+" "+appName)
}

// ParsePushLogTitle 解析推送log
func ParsePushLogTitle(bus *pslog.LogHandlerBus) string {
	ext := bus.TargetExt
	if ext == "" {
		ext = bus.Ext
	}
	projectName, appName := parsePsLogExt(ext)
	return getPushLogTitle(projectName, appName)
}
